package action.resource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import model.Resource;

import org.apache.struts2.ServletActionContext;

import util.Encoding;


import DAO.ResourceDAO;
import DAO.DAOImple.ResourceImple;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class DownloadAction implements Action {
	private String fileName;
	private InputStream inputStream;
	private String contentType;
	
	private Resource resource;
	
	public String execute() {
		ResourceDAO resourceDAO = new ResourceImple();
		resource = resourceDAO.getResourceById(resource.getId());
		
		ServletContext sc = (ServletContext)ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT);
		
	    fileName =sc.getRealPath("/") + resource.getDocPath();
		
		try {
			File file = new File(fileName);
			if(file == null) {
				return ERROR;
			}
			inputStream = new FileInputStream(file);
			int urs = resourceDAO.addDownloadTimes(resource.getId());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		contentType = resource.getDownloadType();
		fileName = resource.getDocName() + "." + resource.getDocType();
		fileName = Encoding.gbkToISO(fileName);
		return SUCCESS;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public Resource getResource() {
		return resource;
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}

}
